package keye.document_manage.util;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.spi.FileSystemProvider;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import keye.document_manage.exception.FileCopyException;

public class FileUtil {

	private static Integer number=1;
	
	public static void setNumber(Integer number) {
		FileUtil.number = number;
	}
	
	public static void write(Path path, String data, OpenOption... options){
		try {
			String m = number+"\t"+data;
			Files.write(path, m.getBytes(), options);
			number++;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean isExistsFiles(String... path){
		if(null ==  path)
			return false;
		for (int i = 0; i < path.length; i++) {
			if(null == path[i])
				return false;
			//TODO 判断文件是否存在，存在性能问题(2016-3-10 11:04:59 说法不准确，一开始连接慢的原因：服务器上的ip地址和数据库中的不一样)
			if(Files.exists(Paths.get(path[i]))){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 复制文件
	 * @param path 源文件路径
	 * @param desPath 目标文件的文件夹路径,必须以File.separator结尾
	 * @return
	 */
	public static int copyFileOne(String path, String desPath) throws FileCopyException {
		if(null ==  path || null == desPath)
			return -1;
		if(!desPath.endsWith(File.separator))
			return 0;
		try {
			Path srcP = Paths.get(path),desP = Paths.get(desPath);
			if(!Files.exists(desP))
				Files.createDirectories(desP);
			if(Files.exists(srcP)){
				desP = Paths.get(desPath+srcP.getFileName());
				Files.copy(srcP, desP, StandardCopyOption.REPLACE_EXISTING);
			}else{
				throw new FileCopyException("源文件不存在！");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1;
	}

	public static void openDirectory(String directoryPath) {
		String[] list = {"explorer.exe", directoryPath};
		ProcessBuilder pb = new ProcessBuilder(list);
		try {
			pb.start();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static void openTxt(String logPath){
		String[] list = {"notepad.exe", logPath};
		ProcessBuilder pb = new ProcessBuilder(list);
		try {
			pb.start();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static int copyFileWindows(String path, String desPath) {
		if(null ==  path || null == desPath)
			return -1;
		if(!desPath.endsWith(File.separator))
			return 0;
		try {
			//cmd.exe /c copy M:\test\t\log2.txt M:\test\t\1
			String[] list = {"cmd.exe","/c","copy",path,desPath};
			ProcessBuilder pb = new ProcessBuilder(list);
			Process p = pb.start();
//			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
//			br.lines().forEach(System.out::println);
			while(p.isAlive()){
//				System.out.println(p.isAlive());
			}
//			if(!p.isAlive())
//				throw new FileCopyException("源文件不存在！");
//			String exec = "cmd.exe /c copy "+path+" "+desPath;
//			System.out.println(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1;
	}
	
	/**
	 * 不复制子目录的文件
	 * @param path
	 * @param desPath
	 * @return
	 */
	public static int copyFile(String path, String desPath,boolean dis) {
		if(null ==  path || null == desPath)
			return -1;
		if(!desPath.endsWith("/"))
			return 0;
		try {
			// Files.readAllBytes(Paths.get(path));
			
			File fl = new File(path);
			File tf = new File(desPath);
			if(!tf.exists()){
				tf.mkdirs();
			}
			
			if (fl.isDirectory()) {
				JProgressBar b = null;
				Path source = null;
				Path target = null;
				File[] fs = fl.listFiles();
				if(dis){
					b = dis(fs.length);
				}
				for (int i = 0; i < fs.length; i++) {
					source = Paths.get(fs[i].getPath());
					target = Paths.get(desPath + fs[i].getName());
					Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
					if(dis){
						b.setValue(i+1);
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public static int copyFile2(String path, String desPath) {
		if(null ==  path || null == desPath)
			return -1;
		if(!desPath.endsWith("/"))
			return 0;
		try {
			// Files.readAllBytes(Paths.get(path));
			File fl = new File(path);
			File tf = new File(desPath);
			if(!tf.exists()){
				tf.mkdirs();
			}
			if (fl.isDirectory()) {
				Path source = null;
				Path target = null;
				File[] fs = fl.listFiles();
				FileSystemProvider provider = provider(Paths.get(fl.getPath()));
				for (int i = 0; i < fs.length; i++) {
					source = Paths.get(fs[i].getPath());
					target = Paths.get(desPath + fs[i].getName());
					provider.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	private static FileSystemProvider provider(Path path) {
		return path.getFileSystem().provider();
	}

	private static JProgressBar dis(final int max){
		final JProgressBar jpb = new JProgressBar(0,max);;
		EventQueue.invokeLater(()-> {
			try {
				JFrame frame = new JFrame();
				frame.setLocationRelativeTo(null);
				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());
				SwingUtilities.updateComponentTreeUI(frame);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setSize(400, 100);
				
				JPanel jp = new JPanel(new BorderLayout());
				jpb.setStringPainted(true);
				jpb.addChangeListener(l->{
					if(!(jpb.getValue()<max))
						frame.dispose();
				});
				jp.add(jpb,BorderLayout.CENTER);
				frame.add(jp,BorderLayout.SOUTH);
				
				frame.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		
		return jpb;
	}
	
	public static void copyFile(String s,String p) {
		Path src = Paths.get(s);
		if(Files.isDirectory(src)){
			try {
				Files.list(src).forEach(v->{
					try {
					copyFileOne(v.toString(), p);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}});
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
	}
	
	
	public static void main(String[] args) {
		long startTime = System.nanoTime();
		//\\\\192.168.1.178\\28\\2001\\0001\\001\\0001.jpg
//		copyFile("\\\\192.168.1.154\\m/test/ww/", "m:/test/wb5"+File.separator);
//		Path p = Paths.get("\\\\192.168.1.154\\m\\test\\ww\\001.jpg");
		try {
			Files.list(Paths.get("M:\\test\\weibo")).forEach(v->copyFileWindows(v.toAbsolutePath().toString(), "M:\\test\\t\\2\\"));
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		long elapsedTime = System.nanoTime() - startTime;
		System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0)
				+ " seconds");		
		
	}
}
